package com.httpserv;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class HttpProcess implements Runnable {
	
	private InputStream in = null;
	private PrintStream out = null;
	private String basePath = null;
	
	public HttpProcess(Socket socket, String basePath){
		this.basePath = basePath;
		try {
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void run() {
		
		String resource = getResource(in);
		
		sendMessage(resource);
	}

	private void sendMessage(String resource) {
		try {
			File file = new File(basePath + resource);
			if(! file.exists()){
				sendErrorMessage("404", "file not found!");
				return;
			}
			
			InputStream in = new FileInputStream(file);
			byte[] buffer = new byte[(int)file.length()];
			in.read(buffer);
		
			out.println("HTTP/1.0 200 queryfile");
			out.println("content-length:" + buffer.length);
			out.println();
			out.write(buffer);
			
			out.flush();
			out.close();
			in.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void sendErrorMessage(String errorCode, String errorMessage) {
		try {
			out.println("HTTP/1.0 " + errorCode + " " + errorMessage);
			out.println("content-type: text/html");
			out.println();
			StringBuffer sb = new StringBuffer();
			sb.append("<html>");
			sb.append("<head>");
			sb.append("<title>Error Message</title>");
			sb.append("</head>");
			sb.append("<body>");
			sb.append("<h1>ErrorCode: " + errorCode + ", ErrorMessage: " + errorMessage + "</h1>");
			sb.append("</body>");
			sb.append("</html>");
			out.write(sb.toString().getBytes());
			
			out.flush();
			out.close();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String getResource(InputStream in) {
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			String line=reader.readLine();
			if(line == null){
				sendErrorMessage("400", "client error!");
				return null;
			}
			String[] arr = line.split(" ");
			if(arr.length != 3){
				sendErrorMessage("400", "client error!");
				return null;
			}
			return arr[1];
		}catch(IOException e){
			e.printStackTrace();
		}
		sendErrorMessage("400", "client error!");
		return null;
	}
	
}
